<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" >
				<el-form-item>
					<el-input v-model="keyword" placeholder="请输入宠物名称"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="keyQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
        <el-form-item>
          <el-button type="primary" @click="listing" :disabled="this.sels.length===0">上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="delist" :disabled="this.sels.length===0">下架</el-button>
        </el-form-item>
			</el-form>
		</el-col>
		<!--列表-->
		<el-table :data="pets" highlight-current-row v-loading="listLoading"
              :row-key="getRowKey" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55" :reserve-selection="true">
			</el-table-column>
			<el-table-column type="index" label="序号" width="60">
			</el-table-column>
			<el-table-column prop="name" label="宠物名称" width="100"align="center">
			</el-table-column>
			<el-table-column prop="costprice" label="成本价" width="70" align="center">
			</el-table-column>
			<el-table-column prop="saleprice" label="市场价" width="70" align="center">
			</el-table-column>
      <el-table-column prop="type.name" label="宠物类型" width="100" align="center">
      </el-table-column>
<!--      <el-table-column prop="resources" label="图片" :show-overflow-tooltip="true" width="150" align="center">-->
<!--      </el-table-column>-->
      <el-table-column prop="state" label="状态" width="100" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.state == 1" style="color: lightseagreen">上架</span>
          <span v-else style="color: crimson">下架</span>
        </template>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" width="150" align="center">
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" width="150" align="center">
      </el-table-column>
      <el-table-column prop="createtime" label="创建时间" width="150" align="center">
      </el-table-column>
      <el-table-column prop="shop.name" label="所属店铺" width="150" align="center">
      </el-table-column>
			<el-table-column prop="user.username" label="领养人" width="100" align="center">
			</el-table-column>

<!--      <el-table-column prop="searchMasterMsg.title" label="寻主标题" :show-overflow-tooltip="true" width="100" align="center">-->
<!--			</el-table-column>-->
			<el-table-column label="操作" width="150" align="center">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :page-size="pageSize"
          :current-page="currentPage"
          :total="totals"
          :page-sizes="[5, 8, 10]"
          style="float:right;">
			</el-pagination>
		</el-col>

		<!--添加修改对话框-->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="宠物名称" prop="name">
					<el-input v-model="saveForm.name" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="成本价格" >
          <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="售卖价格" >
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="宠物类型">
            <el-cascader
                v-model="saveForm.typeId"
                :options="petTypeTree"
                :props="{ checkStrictly: true, label: 'name',value:'id' }"
                clearable></el-cascader>
        </el-form-item>
        <el-form-item label="所属店铺">
          <el-select v-model="saveForm.shopId" placeholder="请选择">
            <el-option
                v-for="item in shops"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资源" >
<!--          <el-input v-model="saveForm.resources" auto-complete="off"></el-input>-->
          <el-upload
              class="upload-demo"
              action="http://localhost:8080/fastDfs"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="fileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
<!--        <el-form-item label="状态">-->
<!--          <el-radio-group v-model="saveForm.state">-->
<!--            <el-radio class="radio" :label="1">上架</el-radio>-->
<!--            <el-radio class="radio" :label="0">下架</el-radio>-->
<!--          </el-radio-group>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="下架时间" >-->
<!--          <el-date-picker-->
<!--              v-model="saveForm.offsaletime"-->
<!--              type="datetime"-->
<!--              placeholder="选择下架时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="上架时间">-->
<!--          <el-date-picker-->
<!--              v-model="saveForm.onsaletime"-->
<!--              type="datetime"-->
<!--              placeholder="选择上架时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->

<!--        <el-form-item label="领养用户">-->
<!--          <el-select v-model="saveForm.userId" placeholder="请选择">-->
<!--            <el-option-->
<!--                v-for="item in users"-->
<!--                :label="item.username"-->
<!--                :value="item.id">-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="简介" prop="intro">
          <!-- v-if="saveForm.petDetail" 修改v-model绑定对象报错问题，v-if对需要显示的数据判断下 -->
          <quill-editor v-model="saveForm.petDetail.intro" v-if="saveForm.petDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
        <el-form-item label="领养须知" prop="orderNotice" >
          <quill-editor  v-model="saveForm.petDetail.adoptNotice" v-if="saveForm.petDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
        <!--        <el-form-item label="寻主标题">-->
<!--          <el-select v-model="saveForm.searchMasterMsgId" placeholder="请选择">-->
<!--            <el-option-->
<!--                v-for="item in searchMasterMsgs"-->
<!--                :label="item.title"-->
<!--                :value="item.id">-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>

import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';

	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getPetListPage, removePet, batchRemovePet, editPet, addPet } from '../../api/api';
import quillConfig from "../../common/js/quill-config";

	export default {
    components: {
      quillEditor
    },
    watch: {
      saveFormVisible(val) { // 当弹窗打开时
        // 重置表单，清空校验信息
        this.$nextTick(() => {
          //  延时到下一帧才开始，也就是页面刚刚渲染结束！！
          this.$refs.saveForm.clearValidate()
        })
      }
    },
		data() {
			return {
        quillOption: quillConfig,
        // 分页相关数据
        currentPage: 1,
        pageSize: 5,
        totals: 0,
        pets: [],
        listLoading: false,
        // 高级查询
        keyword: '',
        // 宠物类型树
        petTypeTree: [],
        // 所有经理
        petTypes: '',
        users: '',
        searchMasterMsgs: '',
        fileList: [],
        // 分页批量选中
        getRowKey(row){
          return row.id;
        },
        // 批量删除
				sels: [],//列表选中列
        shops: '',
				//对话框数据
        title: '',
				saveForm: {
					id: null,
          name: '',
          costprice: null,
          saleprice: null,
          typeId: null,
          resources: '',
          // state: 0,
          offsaletime: '',
          onsaletime: '',
          shopId: null,
          userId: null,
          searchMasterMsgId: null,
          petDetail: {
            intro: '',
            adoptNotice: '',
          },
				},
				saveFormVisible: false,//新增界面是否显示
				saveLoading: false, // 加载框
				saveFormRules: { // 表单项校验
          name: [
            { required: true, message: '请输入宠物名称', trigger: 'blur' }
          ]
				},
			}
		},
		methods: {
      //分页查询
      getPets() {
        let param = {
          pageSize: this.pageSize,
          currentPage: this.currentPage,
          keyword: this.keyword
        };
        this.listLoading = true;
        this.$http.post("/pet", param).then(res=>{
          this.pets = res.data.data
          this.totals = res.data.totals
          this.listLoading = false;
        })
      },
      // 高级查询
      keyQuery(){
        this.currentPage = 1
        this.getPets();
      },
      //选择第几页时触发
      handleCurrentChange(currentPage) {
        this.currentPage = currentPage;
        this.getPets();
      },
      //选择每页显示记录条数
      handleSizeChange(pageSize) {
        this.pageSize = pageSize;
        this.getPets();
      },
      //删除
      handleDel: function (index, row) {
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.delete("/pet/" + row.id).then(res=>{
              if (res.data.success){
                let pageTotal = Math.ceil(this.totals/this.pageSize)
                if (this.currentPage != 1 && this.currentPage == pageTotal && (this.totals - 1)%this.pageSize ==0){
                  this.currentPage = this.currentPage - 1
                }
                this.getPets();
              } else {
                this.$message.error("系统繁忙，请稍后重试！【500】")
              }
          }).catch(res=> {
            this.$message.error("系统繁忙，请稍后重试！【400,404,405】")
          })
          this.listLoading = false;
        }).catch(() => { // 取消

        });
      },
      // 选中改变时
      selsChange: function (sels) {
        this.sels = sels.map(obj => obj.id);
      },
      //批量上架
      listing: function () {
        var ids = this.sels
        this.$confirm('确认上架选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.post("/pet/listing",ids).then(res => {
            this.listLoading = false;
            if(res.data.success){
              this.$message.success("上架成功！");
              this.getPets();
            }else{
              this.$message.error(res.data.message);
            }
          }).catch(res => {
            this.$message.error("系统繁忙，请稍后重试![400]");
          })
        }).catch(() => {
        });
      },
      //批量下架
      delist: function () {
        var ids = this.sels
        this.$confirm('确认下架选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.post("/pet/delist",ids).then(res => {
            this.listLoading = false;
            if(res.data.success){
              this.$message.success("下架成功！");
              this.getPets();
            }else{
              this.$message.error(res.data.message);
            }
          }).catch(res => {
            this.$message.error("系统繁忙，请稍后重试![400]");
          })
        }).catch(() => {
        });
      },
      //批量删除
      batchRemove: function () {
        var ids = this.sels
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.patch("/pet",ids).then(res => {
            this.listLoading = false;
            if(res.data.success){
              //计算总页数
              let totalPage = Math.ceil(this.totals/this.pageSize)
              if(this.currentPage > 1 && this.currentPage==totalPage && (this.totals-this.sels.length)%this.pageSize==0){
                this.currentPage = this.currentPage - 1;
              }
              this.getPets();
            }else{
              this.$message.error("系统繁忙，请稍后重试![500]");
            }
          }).catch(res => {
            this.$message.error("系统繁忙，请稍后重试![400]");
          })
        }).catch(() => {
        });
      },
			//显示编辑界面
			handleEdit: function (index, row) {
        this.title = '编辑'
        this.saveForm = Object.assign({}, row);
        this.getPetTypes();
        this.getShops();
        this.getUsers();
        this.getPetTypeTree();
        this.getSearchMasterMsgs();
        // 对fileList进行处理，用以显示图片
        // 先 清空 - 这个fileList做了绑定，以前是有值【先清空，再添加最新的数据】
        this.fileList = []
        if (this.saveForm.resources) {
          // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/0C/CgAIC2KrUYaAaR-6AADnxcxs4eA746.jpg 对其进行分割
          let arr = this.saveForm.resources.split(',')
          // 循环遍历
          for (let i = 0; i < arr.length; i++) {
            // 从fastDfs文件系统获取资源
            this.fileList.push({'url': 'http://service-file-primary.java.itsource.cn' + arr[i]})
          }
        }
				this.saveFormVisible = true;
			},
			//显示新增界面
			handleAdd: function () {
        this.title = '添加'
        this.saveForm = { // 重置数据
          id: null,
          name: '',
          costprice: null,
          saleprice: null,
          typeId: null,
          resources: '',
          // state: 0,
          offsaletime: '',
          onsaletime: '',
          shopId: null,
          userId: null,
          searchMasterMsgId: null,
          petDetail: {
            intro: '',
            adoptNotice: '',
          },
				};
        this.getPetTypeTree();
        this.getPetTypes();
        this.getShops();
        this.getUsers();
        this.getSearchMasterMsgs();
        this.fileList = [];
        this.saveFormVisible = true;
			},
			//提交按钮
      saveSubmit: function () {
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.saveLoading = true;
              let para = Object.assign({},this.saveForm)
              // 判断parentId
              let temp = para.typeId
              if (temp == null || temp.length == 0){ // 顶级部门
                para.typeId = null;
              } else if (temp.length) { // 子部门 获取id
                para.typeId = temp[temp.length-1]
              }
							this.$http.put("/pet",para).then(res=>{
                this.saveLoading = false;
                this.saveFormVisible = false;
                if (res.data.success){
                  this.getPets()
                  this.$message.success("操作成功！")
                } else {
                  this.$message.error(res.data.message);
                }
              }).catch(res=>{
                this.$message.error("系统繁忙，请稍后重试![400]");
              })
						});
					}
				});
			},
      // 获取所有经理
      getPetTypes(){
        this.$http.get("/petType").then(res => {
          this.petTypes = res.data;
        })
      },
      getShops(){
        this.$http.get("/shop").then(res => {
          this.shops = res.data;
        })
      },
      getUsers(){
        this.$http.get("/user").then(res => {
          this.users = res.data;
        })
      },
      getSearchMasterMsgs(){
        this.$http.get("/searchMasterMsg").then(res => {
          this.searchMasterMsgs = res.data;
        })
      },
      // 获取宠物类型树
      getPetTypeTree(){
        this.$http.get("/petType/petTypeTree").then(res => {
          this.petTypeTree = res.data;
        })
      },
      //文件上传的业务逻辑：上传时机：选择好文件之后就上传
      handleSuccess(response, file, fileList){
        //1.只要把action属性写对了就可以上传了
        //处理resources
        if(this.saveForm.resources){//有值
          this.saveForm.resources = this.saveForm.resources+","+response.resultObj;
        }else{
          this.saveForm.resources = response.resultObj;
        }
        //处理fileList:resources = xx,xx,xx
        // this.fileList=[];//先清空 - 再添加最新的所有该宠物图片
        // if(this.saveForm.resources){
        //   let arr = this.saveForm.resources.split(",");//[xx,xx,xx]
        //   for(var i = 0;i<arr.length;i++){
        //     this.fileList.push({"url":"http://service-file-primary.java.itsource.cn"+arr[i]});
        //   }
        // }
      },
      //文件删除的业务逻辑
      handleRemove(file, fileList) {
        //1.调用删除接口删除fastdfs中的数据 :
        var url = file.url;//http://service-file-primary.java.itsource.cn/group1/M00/00/0C/CgAIC2KrU4qAAy6HAAF5fdD2FCI828.jpg
        var path = url.substring(url.indexOf("/group"));// /group1/M00/00/0C/CgAIC2KrU4qAAy6HAAF5fdD2FCI828.jpg
        this.$http.delete("/fastDfs?path="+path).then(res=>{
          if(res.data.success){
            this.$message.success("删除成功!!!");
          }else{
            this.$message.error("删除失败!!!");
          }
        })
        //2.处理resources
        if(this.saveForm.resources){ // xx,yy,zz
          let arr = this.saveForm.resources.split(","); //[xx,yy,zz]
          for(var i = 0;i<arr.length;i++){
            if(path == arr[i]){//找到了删除的图片
              arr.splice(i,1);
              break;
            }
          }         //[xx,zz]
          this.saveForm.resources = arr.join(","); //xx,zz
        }
        //3.处理fileList
        this.fileList=[];//先清空 - 再添加最新的所有该宠物图片
        if(this.saveForm.resources){
          let arr = this.saveForm.resources.split(",");//[xx,xx,xx]
          for(var i = 0;i<arr.length;i++){
            this.fileList.push({"url":"http://service-file-primary.java.itsource.cn"+arr[i]});
          }
        }
      }

    },
		mounted() {
			this.getPets();
		}
	}

</script>

<style scoped>

</style>